<template>
  <div id="header">
    <a-row>
      <a-col :span="6"> </a-col>
      <a-col :span="12">
        <div class="header-content">
          <h1>寻梦知识库</h1>
        </div>
      </a-col>
      <a-col :span="6">
        <div class="header-content">
          <template v-if="userInfo.userName.length === 0">
            想要添加或是编辑，请先<a-button type="link" @click="showLoginModal">登录</a-button>
          </template>
          <template v-else>
            {{ userInfo.userName }}
            <a-button type="link" @click="logout">退出</a-button>
          </template>
        </div>
      </a-col>
    </a-row>
    <a-modal v-model:visible="loginModalVisible" title="登录" :footer="null">
      <a-form
        ref="formRef"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 14, offset: 4 }"
        :model="loginModalData"
        :rules="loginModalRules"
      >
        <a-form-item label="用户名" name="nickName">
          <a-input v-model:value="loginModalData.nickName" placeholder="请输入用户名" />
        </a-form-item>
        <a-form-item label="密 码" name="pass">
          <a-input-password v-model:value="loginModalData.pass" placeholder="请输入密码" />
        </a-form-item>
        <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
          <a-button type="primary" @click="submitLogin">登录</a-button>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script lang="ts">
import { defineComponent, ref, reactive, toRefs, UnwrapRef, onMounted } from 'vue'
import { ValidateErrorEntity } from 'ant-design-vue/es/form/interface'
import { useStore } from 'vuex'
import { message } from 'ant-design-vue'
import { key } from '@/store'
import { LoginUserInfo } from '@/modules'
import common from '@/api/common'

interface LoginFormState {
  nickName: string
  pass: string
}

export default defineComponent({
  name: 'Header',
  setup() {
    const store = useStore(key)

    const formRef = ref()
    const loginModalVisible = ref<boolean>(false)

    const loginModalData: UnwrapRef<LoginFormState> = reactive({
      nickName: '',
      pass: ''
    })

    const state = reactive({
      userInfo: {
        avatar: '',
        userId: '',
        userName: ''
      }
    })

    onMounted(() => {
      state.userInfo = store.getters.userInfo
      console.log(store.getters.userInfo)
    })

    // 验证规则
    const loginModalRules = {
      nickName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
      pass: [{ required: true, message: '请输入密码', trigger: 'blur' }]
    }

    const showLoginModal = () => {
      loginModalVisible.value = true
    }

    // 登录表单提交
    const submitLogin = () => {
      formRef.value
        .validate()
        .then(async () => {
          const params = {
            nickName: loginModalData.nickName,
            pass: loginModalData.pass
          }
          const result = await common.login(params)
          const { data }: any = result
          const localUser: LoginUserInfo = {
            avatar: data.avatar,
            userId: data.userId,
            userName: data.userName
          }
          store.commit('common/setToken', data.token)
          console.log(store.getters.token)
          store.commit('common/setUserInfo', localUser)
          loginModalVisible.value = false
          message.success('登录成功')
          window.location.reload()
        })
        .catch((error: ValidateErrorEntity<LoginFormState>) => {
          console.log('error', error)
        })
    }

    // 登出
    const logout = async () => {
      store.commit('common/setToken', '')
      store.commit('common/delUserInfo')
      window.location.reload()
    }

    return {
      ...toRefs(state),
      formRef,
      loginModalVisible,
      loginModalData,
      showLoginModal,
      submitLogin,
      loginModalRules,
      logout
    }
  }
})
</script>

<style>
#header {
  flex: 1;
  background-color: #fff;
  text-align: center;
  height: 80px;
}
#header .logo {
  width: 120px;
  height: 31px;
  background: rgba(255, 255, 255, 0.2);
  margin: 16px 24px 16px 0;
  float: left;
}

.logo-img {
  width: 30px;
  height: 30px;
}

.header-content {
  height: 80px;
  line-height: 80px;
}
</style>
